#!/usr/bin/python -B

from string import Template, upper, replace

from ApiUtil import outputCode
from ApiUtil import typeIsVoid

from ApiCodeGen import *

from RegalContextInfo import cond

from RegalDispatchShared import dispatchSourceTemplate, apiDispatchFuncInitCode

##############################################################################################

def apiStaticES2FuncInitCode(apis, args):

  code = '// OpenGL ES 2.0 only\n\n'

  for api in apis:
    if api.name=='gl':
      for function in api.functions:
        if not function.needsContext:
          continue
        if getattr(function,'esVersions',None)==None or 2.0 not in function.esVersions:
          continue
        name   = function.name
        code += '  tbl.r%s = %s;\n' % ( name, name )

  return code

def generateStaticES2Source(apis, args):

  code  = '\n'

  code += '#ifndef REGAL_NAMESPACE\n'
  code += '#error REGAL_STATIC_ES2 requires REGAL_NAMESPACE\n'
  code += '#endif\n\n'

  for api in apis:
    if api.name=='gl':

      for function in api.functions:
        if not function.needsContext:
          continue
        if getattr(function,'esVersions',None)==None or 2.0 not in function.esVersions:
          continue
        name   = function.name
        code += '#undef %s\n' % ( name )

      code += '\n'
      code += 'extern "C"\n'
      code += '{\n'

      for function in api.functions:
        if not function.needsContext:
          continue
        if getattr(function,'esVersions',None)==None or 2.0 not in function.esVersions:
          continue
        params = paramsDefaultCode(function.parameters, True)
        rType  = typeCode(function.ret.type)
        code += '  extern %s REGAL_CALL %s(%s);\n' % (rType, function.name, params)

      code += '}\n'

  substitute = {}

  substitute['LICENSE']       = args.license
  substitute['AUTOGENERATED'] = args.generated
  substitute['COPYRIGHT']     = args.copyright
  substitute['DISPATCH_NAME'] = 'StaticES2'
  substitute['LOCAL_INCLUDE'] = code
  substitute['LOCAL_CODE']    = ''
  substitute['API_DISPATCH_FUNC_DEFINE'] = ''
  substitute['API_DISPATCH_FUNC_INIT'] = apiStaticES2FuncInitCode( apis, args )
  substitute['API_DISPATCH_GLOBAL_FUNC_INIT'] = ''
  substitute['IFDEF'] = '#if REGAL_DRIVER && REGAL_STATIC_ES2\n\n'
  substitute['ENDIF'] = '#endif\n'

  outputCode( '%s/RegalDispatchStaticES2.cpp' % args.srcdir, dispatchSourceTemplate.substitute(substitute))
